<?php

namespace App\Common\Tools\Amqp;

use App\Common\Traits\AmqpTrait;
use Bschmitt\Amqp\Facades\Amqp;
use PhpAmqpLib\Message\AMQPMessage;

class BaseMQ
{
    use AmqpTrait;
    /**
     * 通用的发送消息方法
     * @param $message
     * @param $biz
     * @param int $timeout 单位是秒
     * @return bool|null
     * @throws \Bschmitt\Amqp\Exception\Configuration
     */
    public static function commonPublish($message, string $biz, int $timeout = 0)
    {
        $config     = config($biz, []);
        $routingkey = $config['routing_key'];
        $properties = [
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
        ];
        if (is_array($message)) {
            $message                    = json_encode($message, JSON_UNESCAPED_UNICODE);
            $properties['content_type'] = 'text/json';
        }
        // 发送带有过期时间的消息
        if ($timeout > 0) {
            $properties['expiration'] = $timeout * 1000;
        }
        $qMessage = new AMQPMessage($message, $properties);

        // 死信队列优化
        $config = array_merge($config, self::getAmqpTable());

        return Amqp::publish($routingkey, $qMessage, $config);
    }
}
